# -*- coding: utf-8 -*- 

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################  
#auth.settings.on_failed_authorization = \
#    URL('user',args='not_authorization')
auth.settings.on_failed_authorization = \
     URL(request.application,'default','error')

def error():
    return dict(message=T('you need permissions to access this item'))

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    response.flash = T('Welcome to web2py')
    return dict(message=T('Hello World'))

@auth.requires_login()
@auth.requires(auth.has_membership('create_donor') or auth.has_membership('site_administration'))
def register_new_donor_and_address():
    form=SQLFORM.factory(db.donor,db.address)
    if form.accepts(request.vars):
        id = db.donor.insert(**db.donor._filter_fields(form.vars))
        form.vars.donor=id
        id = db.address.insert(**db.address._filter_fields(form.vars))
        response.flash='Thanks for filling the form'
    return dict(form=form)

def register_new_donor_address_and_address_type():
    form=SQLFORM.factory(db.donor,db.address_type,db.address)
    if form.accepts(request.vars):
        id = db.donor.insert(**db.donor._filter_fields(form.vars))
        form.vars.donor=id
        id = db.address_type.insert(**db.address_type._filter_fields(form.vars))
        form.vars.donor=id
        id = db.address.insert(**db.address._filter_fields(form.vars))
        response.flash=T('New Donor Information Accepted')
    return dict(form=form)


def user():
    """
    exposes:
    http://..../[app]/default/user/login 
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    session.forget()
    return service()
